package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;

    @Override
    @Transactional(readOnly = true)
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
        //找到所有角色列表
        List<Role> allRoleList = roleDao.findAll();
        //找到用户所具有的角色id列表
        List<Long> existRoleIdList = adminRoleDao.findRoleIdsByAdminId(adminId);
        //根据当前用户具有的角色,把所有角色分为两个列表,用户有的,用户没有的并返回
        List<Role> noAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList = new ArrayList<>();
        for (Role role : allRoleList) {
            if(existRoleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else {
                noAssignRoleList.add(role);
            }
        }
        Map roleMap =new HashMap();
        roleMap.put("noAssignRoleList",noAssignRoleList);
        roleMap.put("assignRoleList",assignRoleList);
        return roleMap;
    }

    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
        //删除用户之前绑定的角色
        adminRoleDao.deleteByAdminId(adminId);
        //添加现在更改后的角色(根据数组传过来的角色ID)
        //排除角色ID列表为空的情况
        if(roleIds == null){
            return;
        }

        //遍历角色id列表,一个个的添加
        for (Long roleId : roleIds) {
            if(roleId!=null && !"".equals(roleId)){
                AdminRole userRole = new AdminRole();
                userRole.setRoleId(roleId);
                userRole.setAdminId(adminId);
                adminRoleDao.insert(userRole);
            }
        }

    }

    @Override
    protected BaseDao getEntityDao() {
        return roleDao;
    }
}
